﻿using Dapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace TR.Authoize.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class AuthoizeController : ControllerBase
    {
        [HttpGet]
        public ActionResult Login(string name, string pass)
        {
            string conStr = "Data Source=rm-cn-omn3o8dvy000aako.sqlserver.rds.aliyuncs.com, 1433;Initial Catalog=TR;Persist Security Info=True;User ID=l_123;Password=Ff123456;Encrypt=False;";
            using (SqlConnection connection = new SqlConnection(conStr))
            {

                string sql = "SELECT * FROM rbac_User WHERE U_UserName=@U_UserName and U_Password=@U_Password";
                var user = connection.Query(sql, new { @U_UserName = name, @U_Password = pass }).FirstOrDefault();
                if (user != null)
                {
                    //准备有效载荷
                    var claims = new Claim[] {
                        new Claim("U_UserName",name),
                        new Claim( "U_Password",pass)
                                    };
                    //读取加密key
                    SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SDMC-CJAS1-SAD-DFSFA-SADHJVF-VFSS"));
                    //指定加密算法
                    SigningCredentials signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                    //创建jwt
                    JwtSecurityToken jwtSecurityToken = new JwtSecurityToken(
                        issuer: "http://localhost:5114",//颁发Token的web应用程序地址(当前程序)
                        audience: "http://localhost:5289",//token接收程序的地址(WebApi)
                        claims: claims,
                        expires: DateTime.Now.AddMinutes(1),//1分钟有效
                        signingCredentials: signingCredentials);
                    //生成jwt字符串
                    var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
                    return new JsonResult(token);
                }
                else
                {
                    return new JsonResult("用户名或密码错误");
                }

            }
        }
    }
}
